##
# Library
# by XERO
#

# Load configuration
. ./config.sh

##
# Pause the script and wait for a keypress
#
function pause() {
    # $# -eq 0 tests that no arguments were passed to the function
    if [ $# -eq 0 ]; then
        local msg="Press any key to continue..."
    else
        # Display a custom message
        local msg="$@"
    fi
    read -p "${msg}"
}

##
# Make a directory if it doesn't exist and return its full path
# $1 [in] Relative path to a file or directory.
#         Assume basename is a file if it doesn't exist.
# $2 [out] Fully qualified path to file or directory
#
function md_and_get_full_path() {
    if [ -d "${1}" ]; then
        # Its an existing directory
        pushd "${1}"
        eval "${2}='${PWD}'"
    else
        # Assume its a file
        local dir="`dirname "${1}"`"
        mkdir -p "${dir}"
        pushd "${dir}"
        eval "${2}='${PWD}/`basename "${1}"`'"
    fi
    popd
}

##
# Execute SQL statements from a file
# $1 [in] The name of the SQL file. The file must be in the /sql folder
# $2 [in] The log file to generate
#
function db_exec() {
    # Create the logs directory if it doesn't already exist
    local log
    md_and_get_full_path "../logs/`basename "${2}"`" log
    pushd "..\sql"
    db_login <"`basename "${1}"`" >"${log}" 2>&1
    popd
}

##
# Database login
#
function db_login() {
    mysql --host="${db_host}" --user="${db_user}" --password="${db_password}"
}
